package com.example.demo.service.impl;

import com.example.demo.entity.Comment;
import com.example.demo.mapper.CommentMapper;
import com.example.demo.mapper.PostMapper;
import com.example.demo.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private PostMapper postMapper;

    @Override
    @Transactional
    public Comment createComment(Comment comment) {
        // 检查帖子是否存在
        if (postMapper.selectPostById(comment.getPostId()) == null) {
            throw new RuntimeException("Post not found");
        }

        commentMapper.insertComment(comment);

        // 更新帖子评论数
        postMapper.incrementCommentCount(comment.getPostId());

        return commentMapper.selectCommentById(comment.getCommentId());
    }

    @Override
    public Comment getCommentById(Long commentId) {
        return commentMapper.selectCommentById(commentId);
    }

    @Override
    public List<Comment> getCommentsByPostId(Long postId) {
        return commentMapper.selectCommentsByPostId(postId);
    }

    @Override
    public List<Comment> getCommentsByAuthorId(Long authorId) {
        return commentMapper.selectCommentsByAuthorId(authorId);
    }

    @Override
    @Transactional
    public Comment updateComment(Comment comment) {
        commentMapper.updateComment(comment);
        return commentMapper.selectCommentById(comment.getCommentId());
    }

    @Override
    @Transactional
    public void deleteComment(Long commentId) {
        Comment comment = commentMapper.selectCommentById(commentId);
        if (comment == null) {
            throw new RuntimeException("Comment not found");
        }

        commentMapper.deleteComment(commentId);

        // 更新帖子评论数
        postMapper.decrementCommentCount(comment.getPostId());
    }

    @Override
    @Transactional
    public void deleteCommentsByPostId(Long postId) {
        commentMapper.deleteCommentsByPostId(postId);
    }
}